import {DeleteOutlined, EditOutlined, ExclamationCircleOutlined, PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {PageContainer, ProDescriptions, ProTable,} from '@ant-design/pro-components';
import {Button, Divider, Drawer, message, Modal} from 'antd';
import React, {useRef, useState} from 'react';
import {addMenu, queryMenuList, removeMenu, updateMenu} from "@/pages/system/MenuList/service";
import type {MenuListItem} from "@/pages/system/MenuList/data";
import {tree} from "@/utils/utils";
import CreateMenuForm from "@/pages/system/MenuList/components/CreateMenuForm";
import UpdateMenuForm from "@/pages/system/MenuList/components/UpdateMenuForm";

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: MenuListItem) => {
  const hide = message.loading('正在添加');
  try {
    await addMenu({...fields});
    hide();
    message.success('Added successfully');
    return true;
  } catch (error) {
    hide();
    message.error('Adding failed, please try again!');
    return false;
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: MenuListItem) => {
  const hide = message.loading('Configuring');
  try {
    await updateMenu({...fields});
    hide();

    message.success('Configuration is successful');
    return true;
  } catch (error) {
    hide();
    message.error('Configuration failed, please try again!');
    return false;
  }
};

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param id
 */
const handleRemove = async (id: number) => {
  const hide = message.loading('正在删除');
  if (!id) return true;
  try {
    await removeMenu(id);
    hide();
    message.success('Deleted successfully and will refresh soon');
    return true;
  } catch (error) {
    hide();
    message.error('Delete failed, please try again');
    return false;
  }
};

const TableList: React.FC = () => {

  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<MenuListItem>();

  const showDeleteConfirm = (id: number) => {
    Modal.confirm({
      title: '是否删除记录?',
      icon: <ExclamationCircleOutlined/>,
      content: '删除的记录不能恢复,请确认!',
      onOk() {
        handleRemove(id).then(() => {
          actionRef.current?.reloadAndRest?.();
        });
      },
      onCancel() {
      },
    });
  };

  const columns: ProColumns<MenuListItem>[] = [
    {
      title: '菜单名称',
      dataIndex: 'menuName',
      render: (dom, entity) => {
        return <a onClick={() => setCurrentRow(entity)}>{dom}</a>;
      },
    },
    {
      title: '父id',
      dataIndex: 'parentId',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '路径',
      dataIndex: 'menuUrl',
      hideInSearch: true,
    },
    {
      title: '接口地址',
      dataIndex: 'apiUrl',
      hideInSearch: true,
    },
    {
      title: '类型',
      dataIndex: 'menuType',
      hideInSearch: true,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      hideInSearch: true,
    },
    {
      title: '图标',
      dataIndex: 'menuIcon',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'statusId',
      hideInSearch: true,
      valueEnum: {
        0: {text: '禁用', status: 'Error'},
        1: {text: '正常', status: 'Success'},
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      sorter: true,
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <Button
            type="primary"
            // disabled={!hasPm("/api/system/menu/view")}
            onClick={() => {
              handleUpdateModalVisible(true);
              setCurrentRow(record);
            }}
          >
            <EditOutlined/>编辑
          </Button>
          <Divider type="vertical"/>
          <Button
            type="primary"
            danger
            // disabled={!hasPm("/api/system/menu/delete")}
            onClick={() => {
              showDeleteConfirm(record.id);
            }}
          >
            <DeleteOutlined/>删除
          </Button>
        </>
      ),
    },
  ];

  return (
    <PageContainer header={{title: ""}}>
      <ProTable<MenuListItem, API.PageParams>
        actionRef={actionRef}
        rowKey="id"
        search={false}
        toolBarRender={() => [
          <Button type="primary" key="primary" onClick={() => {
            handleModalVisible(true);
          }}
          >
            <PlusOutlined/>新建菜单
          </Button>,
        ]}
        request={queryMenuList}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            console.log(selectedRows)
          },
        }}
        pagination={false}
        postData={(data) => tree(data, 0, 'parentId')}
      />

      <CreateMenuForm
        onCreate={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            handleModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleModalVisible(false);
          setCurrentRow(undefined);

        }}
        open={createModalVisible}
      />

      <UpdateMenuForm
        onCreate={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        open={updateModalVisible}
        item={currentRow}
      />

      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.menuName && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.menuName}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.menuName,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
